package com.hxkcloud.patient.fragments;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hyphenate.easeui.EaseConstant;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.activitys.ArticleDetailActivity;
import com.hxkcloud.patient.activitys.ChatFragmentActivity;
import com.hxkcloud.patient.activitys.PayActivity;
import com.hxkcloud.patient.activitys.PictureConsultActivity;
import com.hxkcloud.patient.activitys.SearchRecordActivity;
import com.hxkcloud.patient.adapter.PopPayAdapter;
import com.hxkcloud.patient.beans.ConsultMsgShowBean;
import com.hxkcloud.patient.beans.ConsulteBean;
import com.hxkcloud.patient.beans.ConsulteBeanList;
import com.hxkcloud.patient.beans.DoctorPriceBean;
import com.hxkcloud.patient.beans.DoctorPriceListBean;
import com.hxkcloud.patient.beans.NurseBean;
import com.hxkcloud.patient.beans.NurseWholeBean;
import com.hxkcloud.patient.config.UrlConfig;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.ImageOptionUtils;
import com.hxkcloud.patient.utils.ImageUtil;
import com.hxkcloud.patient.utils.StringUtil;
import com.hxkcloud.patient.views.CircleImageView;
import com.hxkcloud.patient.views.FlowLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/12.
 */

public class ConsulteFragment extends BaseFragment implements View.OnClickListener {
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_complete;

    private View view;
    private LinearLayout ll_roots;
    //跳转我的咨询
    private LinearLayout consult_llin;
    //图文咨询和支付
    private TextView tv_consult;
    private TextView tv_pay;


    private View payView;
    private PopupWindow pop_pay;
    private GridView gv_shows;
    private TextView tv_payfor;
    private TextView tv_detaile;
//    private String[] data = {"200元/20次","1000元/200次","500元/50次"};
    private PopPayAdapter popPayAdapter;
    private LinearLayout pop_payLiner;

    private List<DoctorPriceBean> datas;
    private List<DoctorPriceBean> data;
    private DoctorPriceListBean doctorPriceListBean;
    private int numbers = 0;
//    private ObjectResultBean<DoctorPriceListBean> doctorPriceList;
    private ConsulteBeanList consulteBeanList;
    private List<ConsulteBean> consult_list;

    private TextView doctor_group;
    private TextView count;
    private TextView nurse_name;
    private CircleImageView nures_head;
    private FlowLayout flowLayout;
    private int counts=0;

    private TextView consult_free;

    private int pageIndex = 1;
    private int pageSize = 15;
    private ArrayList<NurseBean> nurses;

    private LinearLayout ll_doctorteam;

    private TextView tv_msg_consult;
    private TextView tv_msg_nurse;

    private ConsultMsgShowBean consultMsgShowBean;

    public static ConsulteFragment instance;
    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what){
            case MessageCode.NETWORKCODE_WZUSERDOCTORPRICELIST_SUCCESS:
                //Log.i("---doctorn--->","doctor:"+msg.toString());
                if (msg.obj!=null){
                    //doctorPriceList = (ObjectResultBean<DoctorPriceListBean>) msg.obj;
                    Log.i("---doctor--->","doctor:"+msg.obj.toString());
                    doctorPriceListBean = (DoctorPriceListBean) msg.obj;

                    //data = doctorPriceList.getData().getDoctorPrice();
//                    for (int i=0;i<doctorPriceListBean.size)
                    data.clear();
                    datas = doctorPriceListBean.getDoctorPrice();
                    for (int i=0;i<datas.size();i++){
                        data.add(datas.get(i));
                        if (datas.get(i).getIsReferral().equals("1")){
                            numbers = i;
                            tv_detaile.setText(data.get(i).getDescribe());
                        }
                    }
                }

                popPayAdapter.notifyDataSetChanged();
                popPayAdapter.changeSelected(numbers);
                Log.i("---doctorPriceBean--->","doctorPriceBean:"+data.size()+":"+data.toString());

                break;
            case MessageCode.NETWORKCODE_WZUSERDOCTORPRICELIST_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                  toastMsg(R.string.datagetfail);
                }
                break;
            case MessageCode.NETWORKCODE_USERCOUNT_SUCCESS:
                if (msg.obj!=null){
                    Log.i("---consult_list--->"," msg.obj:"+ msg.obj.toString());
                    consult_list.clear();
                    consulteBeanList = (ConsulteBeanList) msg.obj;
                    consult_list.addAll(consulteBeanList.getJobGroup());

                    //Log.i("---consult_list--->","consult_list:"+consult_list.size()+":"+consult_list.toString());
                    if (consult_list!=null){
                        doctor_group.setText(consult_list.get(0).getGroup());
                        counts = consult_list.get(0).getCount();
                        count.setText(counts+"/"+consult_list.get(0).getNumber());
                        Log.i("---count--->"," count:"+ count.getText().toString());
                        nurse_name.setText(consult_list.get(0).getName());
                     //  nures_head.setImageBitmap();
                        Log.i("---consult_list--->"," consult_list:"+ consult_list.get(0).getPhotoPath());
                        //地址拼接
                        imageLoader.displayImage(UrlConfig.image_host + consult_list.get(0).getPhotoPath(), nures_head, ImageOptionUtils.getInstance().getNurseHeadOptions());
                        flowLayout.removeAllViews();
                        String jobPlace = consult_list.get(0).getJobPlace();
                        String departmentName =  consult_list.get(0).getDepartmentName();
                        String hobby = consult_list.get(0).getHobby();
                        String jobLevel = consult_list.get(0).getJobLevel();
                        List<String> jobs = new ArrayList<>();
                        if (!TextUtils.isEmpty(jobPlace)){
                            jobs.add(jobPlace);
                        }
                        if (!TextUtils.isEmpty(departmentName)){
                            jobs.add(departmentName);
                        }
                        if (!TextUtils.isEmpty(hobby)){
                            jobs.add(hobby);
                        }
                        if (!TextUtils.isEmpty(jobLevel)){
                            jobs.add(jobLevel);
                        }
                        Log.i("--jobs-->",jobs.toString());
                        if (jobs!=null&&jobs.size()>0){
                            for (int i=0;i<jobs.size();i++){
                                addTv(1,i,jobs.get(i),flowLayout);
                            }
                        }else {
                            addTvnull(1,flowLayout);
                        }

                    }else {
                        toastMsg(R.string.datagetfail);
                    }

                }

                break;
            case MessageCode.NETWORKCODE_USERCOUNT_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datagetfail);
                }
                break;
            //护士那块
            case MessageCode.NETWORKCODE_GETDEPARTMENTNURSELIST_SUCCESS:
                if (msg.obj != null) {
                    NurseWholeBean nurseWhole = (NurseWholeBean) msg.obj;
                    nurses.clear();
                    nurses.addAll(nurseWhole.getList());
                } else {
                    toastMsg(R.string.departmentnursesgetfail);
                }
                break;
            case MessageCode.NETWORKCODE_GETDEPARTMENTNURSELIST_FAILURE:
                toastMsg("护士信息获取失败");
                break;

            case MessageCode.NETWORKCODE_CHECKCONSULTMSG_SUCCESS:
                if (msg.obj!=null){
                    consultMsgShowBean = (ConsultMsgShowBean) msg.obj;
                    int count = consultMsgShowBean.getCount();
                    if (count>0){
                        tv_msg_consult.setVisibility(View.VISIBLE);
                       // tv_msg_nurse.setVisibility(View.VISIBLE);
                        tv_msg_consult.setText(count+"");
                      //  tv_msg_nurse.setText(count+"");
                    }else {
                        tv_msg_consult.setVisibility(View.INVISIBLE);
                       // tv_msg_nurse.setVisibility(View.INVISIBLE);
                    }
                }
                break;
            case MessageCode.NETWORKCODE_CHECKCONSULTMSG_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datagetfail);
                }
                break;

        }
    }

    public static ConsulteFragment getInstance() {
        return instance;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_consulte, container, false);
        data = new ArrayList<>();
        consult_list = new ArrayList<>();
        nurses = new ArrayList<>();
        initView();
        showPayFor();
        initData();
        initListener();
        popPayAdapter.notifyDataSetChanged();
        instance = this;
        return view;
    }
//    private boolean showIcon;

    public void showPoint(boolean show) {
        //showIcon=show;
        YjhApplication.getInstance().showMsg(tv_msg_nurse);

    }


    private void showPayFor() {
            View payView = LayoutInflater.from(mContext).inflate(R.layout.popwinds_consult_pay,null);
            gv_shows = (GridView) payView.findViewById(R.id.popwinds_gridview_pay);
            tv_payfor = (TextView) payView.findViewById(R.id.tv_consult_pay_click);
            tv_detaile = (TextView) payView.findViewById(R.id.tv_detailedinformation);
            pop_payLiner = (LinearLayout) payView.findViewById(R.id.poppay_layout);
            popPayAdapter = new PopPayAdapter(mContext,data);
            gv_shows.setAdapter(popPayAdapter);
            gv_shows.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    popPayAdapter.changeSelected(position);
                    tv_detaile.setText(data.get(position).getDescribe());
                    numbers = position;
                }
            });
            tv_payfor.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent payShapping  = new Intent(getActivity(),PayActivity.class);
                    payShapping.putExtra("price",data.get(numbers).getPrice()+"");
                    payShapping.putExtra("count",data.get(numbers).getCount()+"");
                    Log.i("data------>","price:"+data.get(numbers).getPrice()+" count:"+data.get(numbers).getCount());
                    startActivity(payShapping);
                    pop_pay.dismiss();
                }
            });
            pop_pay = new PopupWindow(payView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
            pop_pay.setFocusable(true);
            pop_pay.setOutsideTouchable(true);
            pop_pay.setTouchable(true);
            pop_pay.setBackgroundDrawable(new BitmapDrawable());
            pop_pay.setAnimationStyle(R.style.popupwindow_anim_default);
            pop_pay.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    for (int i=0;i<datas.size();i++){
                        if (datas.get(i).getIsReferral().equals("1")){
                            numbers = i;
                            tv_detaile.setText(data.get(i).getDescribe());
                        }
                    }
                    popPayAdapter.changeSelected(numbers);
                    BrightnessUtils.lightOn(getActivity());
                }
            });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_consult_picture:
                Intent pictureIntent = new Intent(mContext,PictureConsultActivity.class);
                //pictureIntent.putExtra("count",count);
                startActivity(pictureIntent);
                break;
            case R.id.consulte_free:
                StringUtil.zhugeTrack(mContext, "责任护士区域中的咨询按钮", "统计咨询中发送信息按钮点击数");
                if (!TextUtils.isEmpty(nurses.get(0).getTel())){
                    Intent iChat = new Intent(mContext, ChatFragmentActivity.class);
                    iChat.putExtra(EaseConstant.EXTRA_USER_ID, "ejh" + nurses.get(0).getTel());
                    String nursesName = nurses.get(0).getName();
                    if (nursesName.length()>8){
                        nursesName = nursesName.substring(0,8)+"...";
                    }
                    // nurses.get(0).getName().substring(0, 1) + "护士"
                    iChat.putExtra("name",nursesName);
//                iChat.putExtra("easeuser","ejh"+nurses.get(position).getTel());
                    startActivity(iChat);
                }else {
                    toastMsg("护士信息获取失败");
                }
                break;
            case R.id.consult_llin://我的咨询
                Intent consultIntent = new Intent(mContext, SearchRecordActivity.class);
                startActivity(consultIntent);
                break;
            case R.id.tv_consult_payfor:
                BrightnessUtils.lightOff(getActivity());
                pop_pay.showAtLocation(ll_roots, Gravity.BOTTOM,0,0);
                break;
            case R.id.consulte_doctor_team:
                Intent articleIntent = new Intent(mContext, ArticleDetailActivity.class);
                articleIntent.putExtra("articleId","645");
                startActivity(articleIntent);
                break;

        }
    }


    @Override
    protected void initView() {
        ll_title = (LinearLayout) view.findViewById(R.id.ll_title);
        iv_back = (ImageView) view.findViewById(R.id.iv_title_back);
        tv_title = (TextView) view.findViewById(R.id.tv_title_title);
        tv_complete = (TextView) view.findViewById(R.id.tv_title_func);

        setTitlePadding(ll_title);
        tv_title.setText("咨询");
        consult_llin = (LinearLayout) view.findViewById(R.id.consult_llin);
        ll_roots = (LinearLayout) view.findViewById(R.id.activity_consult);
        tv_consult = (TextView) view.findViewById(R.id.tv_consult_picture);
        tv_pay = (TextView) view.findViewById(R.id.tv_consult_payfor);

        doctor_group = (TextView) view.findViewById(R.id.consulte_group);
        count = (TextView) view.findViewById(R.id.consulte_count);
        nurse_name = (TextView) view.findViewById(R.id.nurse_name);
        nures_head = (CircleImageView) view.findViewById(R.id.nurse_image);
        flowLayout = (FlowLayout) view.findViewById(R.id.flowlayout_consulte);
        consult_free = (TextView) view.findViewById(R.id.consulte_free);
        ll_doctorteam = (LinearLayout) view.findViewById(R.id.consulte_doctor_team);

        tv_msg_consult = (TextView) view.findViewById(R.id.consult_msg_number);
        tv_msg_nurse = (TextView) view.findViewById(R.id.consult_msg_numbers);
    }

    @Override
    protected void initListener() {
        tv_consult.setOnClickListener(this);
        consult_free.setOnClickListener(this);
        tv_pay.setOnClickListener(this);
        ll_doctorteam.setOnClickListener(this);
        consult_llin.setOnClickListener(this);
    }
    public void refresh(){
        loading();
        YjhApplication.getInstance().showMsg(tv_msg_nurse);
        YiJiaHuNetWorkUtils.getUserDoctorPriceList(handler);
        YiJiaHuNetWorkUtils.UserCount(loginInfo.getUserId(),handler);
        YiJiaHuNetWorkUtils.getNurseList(loginInfo.getDepartmentId(), pageIndex, pageSize, handler);
        YiJiaHuNetWorkUtils.checkConsultNewMsg(loginInfo.getUserId(),handler);
    }
    @Override
    protected void initData() {
//        loading();
//        YiJiaHuNetWorkUtils.getUserDoctorPriceList(handler);
//        YiJiaHuNetWorkUtils.UserCount(loginInfo.getUserId(),handler);
//        YiJiaHuNetWorkUtils.getNurseList(loginInfo.getDepartmentId(), pageIndex, pageSize, handler);
//        YiJiaHuNetWorkUtils.checkConsultNewMsg(loginInfo.getUserId(),handler);
    }

    @Override
    public void onResume() {
        super.onResume();

        refresh();

        /*
        loading();
        YjhApplication.getInstance().showMsg(tv_msg_nurse);
        YiJiaHuNetWorkUtils.getUserDoctorPriceList(handler);
        YiJiaHuNetWorkUtils.UserCount(loginInfo.getUserId(),handler);
        YiJiaHuNetWorkUtils.getNurseList(loginInfo.getDepartmentId(), pageIndex, pageSize, handler);
        YiJiaHuNetWorkUtils.checkConsultNewMsg(loginInfo.getUserId(),handler);
        */
    }
    private void addTv(int group ,int child ,String text,FlowLayout flow){
        TextView tv = new TextView(mContext);
        ViewGroup.MarginLayoutParams lp_tv = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        int dp5 = ImageUtil.dip2px(5,mContext);
        lp_tv.leftMargin = dp5;
        lp_tv.topMargin = dp5;
        tv.setLayoutParams(lp_tv);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
        tv.setTextColor(mContext.getResources().getColor(R.color.grey_text1));
        if (text.length() < 4) {
            tv.setPadding(ImageUtil.dip2px(12, mContext), dp5, ImageUtil.dip2px(12, mContext), dp5);
        } else {
            tv.setPadding(dp5, dp5, dp5, dp5);
        }
        tv.setBackgroundResource(R.drawable.shape_patientinfoback);
        tv.setText(text);
        tv.setId((group * 100) + child);
        tv.setOnClickListener(this);

        flow.addView(tv);
    }
    private void addTvnull(int group, FlowLayout flow) {
        TextView tv = new TextView(mContext);
        ViewGroup.MarginLayoutParams lp_tv = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int dp5 = ImageUtil.dip2px(5, mContext);
        lp_tv.leftMargin = dp5;
        lp_tv.topMargin = dp5;
        tv.setLayoutParams(lp_tv);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        tv.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
        tv.setPadding(dp5, dp5, dp5, dp5);
        tv.setText(getResources().getString(R.string.havenotnow));
        flow.addView(tv);
    }


}
